import { Module } from 'vuex'
import { AllStateTypes } from '../../types'
import { UserStateTypes } from './types'
import { getToken, setToken, removeToken } from '@/utils/auth'
import loginApi from '@/api/login'

const userModule: Module<UserStateTypes, AllStateTypes> = {
  namespaced: true,
  state: {
    token: getToken() as string,
    loginTime: '',
    roles: [],
    data: null,
    isReload: true,
    actionKey: '',
  },
  mutations: {
    SET_TOKEN: (state: UserStateTypes, token: string) => {
      state.token = token
    },
    SET_DATA(state: UserStateTypes, datas: any) {
      state.data = datas
    },
    SET_ISRELOAD(state, data) {
      state.isReload = data
    },
    SET_ACTIONKEY(state, data) {
      state.actionKey = data
    },
  },
  getters: {
    token: (state) => state.token,
    isReload: (state) => state.isReload,
  },
  actions: {
    Login: async ({ commit, dispatch }, userInfo) => {
      const res: any = await loginApi.login(userInfo)
      console.log(res, 'reslogin')
      if (res.status === 200) {
        if (res.data.code != '10000') {
          return res.data
        }
        commit('SET_TOKEN', res.data.token)
        setToken(res.data.token)
        commit('SET_ACTIONKEY', res.data.data.permissionActionKeyText)
        localStorage.userInfo = JSON.stringify(res.data.data)
        return res.data
      }
    },
    loginCode: async ({ commit, dispatch }, userInfo) => {
      const res: any = await loginApi.loginCode(userInfo)
      console.log(res, 'reslogin')
      if (res.status === 200) {
        if (res.data.code != '10000') {
          return res.data
        }
        commit('SET_TOKEN', res.data.token)
        setToken(res.data.token)
        commit('SET_ACTIONKEY', res.data.data.permissionActionKeyText)
        localStorage.userInfo = JSON.stringify(res.data.data)
        return res.data
      }
    },
    getMenus: async (store, data) => {
      const res: any = await loginApi.getUserMuenus()
      if (res.code === 200) return res
      return res
    },
    logout: async (store, flag?: number) => {
      // const res: any = await loginApi.logout()
      // if (res.code === 200) {
      //   localStorage.removeItem('userInfo')
      //   router.push('/login')
      //   removeToken()
      //   return
      // }
      localStorage.removeItem('userInfo')
      removeToken()
      if (flag) store.commit('SET_ISRELOAD', false)
      return true
    },
  },
}
export default userModule
